<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="grpc,微服务," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="简介&amp;emsp;&amp;emsp;gRPC 是由 google 开发的一款现代高性能开源RPC框架，基于HTTP/2标准设计，支持双向流、流控、头部压缩、单TCP连接上的多路复用等特性，使得在移动设备上表现更好、更省电和节省空间占用。并且支持插件式扩展负载均衡、服务跟踪、健康检查、认证等机制。 &amp;emsp;&amp;emsp;主要应用场景  微服务架构的跨语言服务调用 移动设备、浏览器需要连接调用后台服务 生成">
<meta name="keywords" content="grpc,微服务">
<meta property="og:type" content="article">
<meta property="og:title" content="grpc入门指南">
<meta property="og:url" content="http://riverlee.cc/2017/08/22/grpc-guide/index.html">
<meta property="og:site_name" content="River Lee">
<meta property="og:description" content="简介&amp;emsp;&amp;emsp;gRPC 是由 google 开发的一款现代高性能开源RPC框架，基于HTTP/2标准设计，支持双向流、流控、头部压缩、单TCP连接上的多路复用等特性，使得在移动设备上表现更好、更省电和节省空间占用。并且支持插件式扩展负载均衡、服务跟踪、健康检查、认证等机制。 &amp;emsp;&amp;emsp;主要应用场景  微服务架构的跨语言服务调用 移动设备、浏览器需要连接调用后台服务 生成">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://riverlee.cc/uploads/grpc/grpc-arch.png">
<meta property="og:updated_time" content="2017-08-23T01:54:00.818Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="grpc入门指南">
<meta name="twitter:description" content="简介&amp;emsp;&amp;emsp;gRPC 是由 google 开发的一款现代高性能开源RPC框架，基于HTTP/2标准设计，支持双向流、流控、头部压缩、单TCP连接上的多路复用等特性，使得在移动设备上表现更好、更省电和节省空间占用。并且支持插件式扩展负载均衡、服务跟踪、健康检查、认证等机制。 &amp;emsp;&amp;emsp;主要应用场景  微服务架构的跨语言服务调用 移动设备、浏览器需要连接调用后台服务 生成">
<meta name="twitter:image" content="http://riverlee.cc/uploads/grpc/grpc-arch.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: 'River'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://riverlee.cc/2017/08/22/grpc-guide/"/>





  <title>grpc入门指南 | River Lee</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">River Lee</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">http://river.oschina.io <br> https://riverlee.cc</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://riverlee.cc/2017/08/22/grpc-guide/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="River">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="River Lee">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">grpc入门指南</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-22T14:48:17+08:00">
                2017-08-22
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/grpc/" itemprop="url" rel="index">
                    <span itemprop="name">grpc</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h1><p>&emsp;&emsp;gRPC 是由 google 开发的一款现代高性能开源RPC框架，基于HTTP/2标准设计，支持双向流、流控、头部压缩、单TCP连接上的多路复用等特性，使得在移动设备上表现更好、更省电和节省空间占用。并且支持插件式扩展负载均衡、服务跟踪、健康检查、认证等机制。</p>
<p>&emsp;&emsp;<strong>主要应用场景</strong></p>
<ul>
<li>微服务架构的跨语言服务调用</li>
<li>移动设备、浏览器需要连接调用后台服务</li>
<li>生成高效的客户端类库</li>
</ul>
<p>&emsp;&emsp;<strong>核心特性</strong></p>
<ul>
<li>支持10种开发语言（C++、Java、Python、Go、Ruby、Node.js、C#、Objective-C、Andriod Java、PHP）</li>
<li>高效的对接方式和服务定义框架</li>
<li>基于HTTP/2传输的双向流设计</li>
<li>支持插件式实现认证、跟踪、负载均衡和健康检查等服务治理功能</li>
</ul>
<h1 id="基本原理"><a href="#基本原理" class="headerlink" title="基本原理"></a>基本原理</h1><p>&emsp;&emsp;gRPC本质上也是典型的RPC技术实现，客户端可以直接调用不同机器上的服务端方法，构成基本的分布式应用。客户端和服务端程序可以运行在多种环境中，用不同的开发语言来实现，交互接口的定义通过IDL描述（默认是protocol buffers）<br><img src="/uploads/grpc/grpc-arch.png" alt="&quot;grpc architecture&quot;"><br>&emsp;&emsp;基于Protocol buffers（proto3版本）定义一个调用参数Proto Request和一个可选的返回值Protocol Response，一个接口，然后基于protoc工具来编译.proto文件生成不同的开发语言源代码。gRPC框架在底层已经为你解决基本的通讯、编码、方法调用等问题，使用者调用客户端的Stub代码就和调用本地的代码一样，完全透明，无需关心技术细节。</p>
<hr>
<h1 id="Java示例入门"><a href="#Java示例入门" class="headerlink" title="Java示例入门"></a>Java示例入门</h1><div class="note primary"><p><em>基本要求： JDK 7+ </em></p></div>
<h2 id="建立一个Maven工程"><a href="#建立一个Maven工程" class="headerlink" title="建立一个Maven工程"></a>建立一个Maven工程</h2><p>&emsp;&emsp;在 pom 文件的 dependencies 中引入依赖grpc库<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>io.grpc<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>grpc-all<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">version</span>&gt;</span>1.5.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;在 pom 文件的 build 中定义protoc maven插件，用来自动编译我们的proto文件<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">build</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">extensions</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">extension</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>kr.motd.maven<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>os-maven-plugin<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">version</span>&gt;</span>1.5.0.Final<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">extension</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">extensions</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">plugins</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">plugin</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.xolstice.maven.plugins<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>protobuf-maven-plugin<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">version</span>&gt;</span>0.5.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">configuration</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">protocArtifact</span>&gt;</span>com.google.protobuf:protoc:3.3.0:exe:$&#123;os.detected.classifier&#125;<span class="tag">&lt;/<span class="name">protocArtifact</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">pluginId</span>&gt;</span>grpc-java<span class="tag">&lt;/<span class="name">pluginId</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">pluginArtifact</span>&gt;</span>io.grpc:protoc-gen-grpc-java:1.4.0:exe:$&#123;os.detected.classifier&#125;<span class="tag">&lt;/<span class="name">pluginArtifact</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">executions</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">execution</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">goals</span>&gt;</span></div><div class="line">						<span class="tag">&lt;<span class="name">goal</span>&gt;</span>compile<span class="tag">&lt;/<span class="name">goal</span>&gt;</span></div><div class="line">						<span class="tag">&lt;<span class="name">goal</span>&gt;</span>compile-custom<span class="tag">&lt;/<span class="name">goal</span>&gt;</span></div><div class="line">					<span class="tag">&lt;/<span class="name">goals</span>&gt;</span></div><div class="line">				<span class="tag">&lt;/<span class="name">execution</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">executions</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">plugin</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">plugins</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">build</span>&gt;</span></div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;注：<em>前面简介提到 grpc 当前版本为 1.5.0，都是基于 protobuf3 版本实现的。这里要注意一下 protoc 和 protoc-gen-grpc-java 2个插件的版本要对得上，如果你使用的版本较低的话，可以去 maven 中央仓库查一下这二者的依赖关系，插件运行异常大多数原因和这个版本对不上有关系。</em></p>
<h2 id="编写proto文件"><a href="#编写proto文件" class="headerlink" title="编写proto文件"></a>编写proto文件</h2><p>&emsp;&emsp;在maven工程下建立一个目录 src/main/proto，用来保存所有的 .proto 文件，上面指定的 maven 插件可以自动生成对应的 java 代码，我们按官方给的示例来编写 hello.proto 文件如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// The greeting service definition.</span></div><div class="line">service Greeter &#123;</div><div class="line">  <span class="comment">// Sends a greeting</span></div><div class="line">  <span class="function">rpc <span class="title">SayHello</span> <span class="params">(HelloRequest)</span> <span class="title">returns</span> <span class="params">(HelloReply)</span> </span>&#123;&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// The request message containing the user's name</span></div><div class="line">message HelloRequest &#123;</div><div class="line">  string name = <span class="number">1</span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// The response message containing the greetings</span></div><div class="line">message HelloReply &#123;</div><div class="line">  string message = <span class="number">1</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;编译方式：</p>
<ul>
<li>直接在工程目录下运行 mvn clean compile 命令</li>
<li>在 Eclipse 中选中项目 –&gt; Run As –&gt; Maven build… –&gt; Goals 填入 clean compile 确认执行</li>
</ul>
<p>&emsp;&emsp;默认情况下会在工程下生成 <font color="#0099ff">target/generated-sources/protobuf/grpc-java</font> 和 <font color="#0099ff">target/generated-sources/protobuf/java</font> 二个目录，如果这2个目录不是Eclipse源代码目录的话，需要手工设置一下，保证整个项目编译无误。</p>
<h2 id="代码示例"><a href="#代码示例" class="headerlink" title="代码示例"></a>代码示例</h2><p><strong>实现grpc接口</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GreeterImpl</span> <span class="keyword">implements</span> <span class="title">GreeterGrpc</span>.<span class="title">Greeter</span> </span>&#123;</div><div class="line">        </div><div class="line">	<span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sayHello</span><span class="params">(HelloRequest req, StreamObserver&lt;HelloReply&gt; responseObserver)</span> </span>&#123;</div><div class="line">    	System.out.println(<span class="string">"call sayHello"</span>);</div><div class="line">        HelloReply reply = HelloReply.newBuilder().setMessage(<span class="string">"Hello "</span> + req.getName()).build();</div><div class="line">        responseObserver.onNext(reply);</div><div class="line">        responseObserver.onCompleted();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;注意常规的单向调用 responseObserver.onNext(reply); 和 responseObserver.onCompleted(); 这二个调用都是必须的固定套路。后面有机会再详细讲解一下grpc的不同调用模式细节。</p>
<p><strong>Server端代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldServer</span> </span>&#123;</div><div class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger logger = Logger.getLogger(HelloWorldServer.class.getName());</div><div class="line"></div><div class="line">  <span class="keyword">private</span> Server server;</div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">    <span class="comment">/* The port on which the server should run */</span></div><div class="line">    <span class="keyword">int</span> port = <span class="number">50051</span>;</div><div class="line">    server = ServerBuilder.forPort(port)</div><div class="line">        .addService(<span class="keyword">new</span> GreeterImpl())</div><div class="line">        .build()</div><div class="line">        .start();</div><div class="line">    logger.info(<span class="string">"Server started, listening on "</span> + port);</div><div class="line">    Runtime.getRuntime().addShutdownHook(<span class="keyword">new</span> Thread() &#123;</div><div class="line">      <span class="meta">@Override</span></div><div class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="comment">// Use stderr here since the logger may have been reset by its JVM shutdown hook.</span></div><div class="line">        System.err.println(<span class="string">"*** shutting down gRPC server since JVM is shutting down"</span>);</div><div class="line">        HelloWorldServer.<span class="keyword">this</span>.stop();</div><div class="line">        System.err.println(<span class="string">"*** server shut down"</span>);</div><div class="line">      &#125;</div><div class="line">    &#125;);</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">stop</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">if</span> (server != <span class="keyword">null</span>) &#123;</div><div class="line">      server.shutdown();</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="comment">/**</span></div><div class="line"><span class="comment">   * Await termination on the main thread since the grpc library uses daemon threads.</span></div><div class="line"><span class="comment">   */</span></div><div class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">blockUntilShutdown</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</div><div class="line">    <span class="keyword">if</span> (server != <span class="keyword">null</span>) &#123;</div><div class="line">      server.awaitTermination();</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="comment">/**</span></div><div class="line"><span class="comment">   * Main launches the server from the command line.</span></div><div class="line"><span class="comment">   */</span></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, InterruptedException </span>&#123;</div><div class="line">    <span class="keyword">final</span> HelloWorldServer server = <span class="keyword">new</span> HelloWorldServer();</div><div class="line">    server.start();</div><div class="line">    server.blockUntilShutdown();</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>Client端代码</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldClient</span> </span>&#123;</div><div class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger logger = Logger.getLogger(HelloWorldClient.class.getName());</div><div class="line"></div><div class="line">  <span class="keyword">private</span> <span class="keyword">final</span> ManagedChannel channel;</div><div class="line">  <span class="keyword">private</span> <span class="keyword">final</span> GreeterGrpc.GreeterBlockingStub blockingStub;</div><div class="line"></div><div class="line">  <span class="comment">/** Construct client connecting to HelloWorld server at &#123;<span class="doctag">@code</span> host:port&#125;. */</span></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="title">HelloWorldClient</span><span class="params">(String host, <span class="keyword">int</span> port)</span> </span>&#123;</div><div class="line">    <span class="keyword">this</span>(ManagedChannelBuilder.forAddress(host, port)</div><div class="line">        <span class="comment">// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid</span></div><div class="line">        <span class="comment">// needing certificates.</span></div><div class="line">        .usePlaintext(<span class="keyword">true</span>)</div><div class="line">        .build());</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="comment">/** Construct client for accessing RouteGuide server using the existing channel. */</span></div><div class="line">  HelloWorldClient(ManagedChannel channel) &#123;</div><div class="line">    <span class="keyword">this</span>.channel = channel;</div><div class="line">    blockingStub = GreeterGrpc.newBlockingStub(channel);</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">shutdown</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</div><div class="line">    channel.shutdown().awaitTermination(<span class="number">5</span>, TimeUnit.SECONDS);</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="comment">/** Say hello to server. */</span></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">greet</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">    logger.info(<span class="string">"Will try to greet "</span> + name + <span class="string">" ..."</span>);</div><div class="line">    HelloRequest request = HelloRequest.newBuilder().setName(name).build();</div><div class="line">    HelloReply response;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">      response = blockingStub.sayHello(request);</div><div class="line">    &#125; <span class="keyword">catch</span> (StatusRuntimeException e) &#123;</div><div class="line">      logger.log(Level.WARNING, <span class="string">"RPC failed: &#123;0&#125;"</span>, e.getStatus());</div><div class="line">      <span class="keyword">return</span>;</div><div class="line">    &#125;</div><div class="line">    logger.info(<span class="string">"Greeting: "</span> + response.getMessage());</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="comment">/**</span></div><div class="line"><span class="comment">   * Greet server. If provided, the first element of &#123;<span class="doctag">@code</span> args&#125; is the name to use in the</span></div><div class="line"><span class="comment">   * greeting.</span></div><div class="line"><span class="comment">   */</span></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">    HelloWorldClient client = <span class="keyword">new</span> HelloWorldClient(<span class="string">"localhost"</span>, <span class="number">50051</span>);</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">      <span class="comment">/* Access a service running on the local machine on port 50051 */</span></div><div class="line">      String user = <span class="string">"world"</span>;</div><div class="line">      <span class="keyword">if</span> (args.length &gt; <span class="number">0</span>) &#123;</div><div class="line">        user = args[<span class="number">0</span>]; <span class="comment">/* Use the arg as the name to greet if provided */</span></div><div class="line">      &#125;</div><div class="line">      client.greet(user);</div><div class="line">    &#125; <span class="keyword">finally</span> &#123;</div><div class="line">      client.shutdown();</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p><strong>运行</strong></p>
<ol>
<li>运行 HelloWorldServer  <em>程序会一直运行监听50051端口</em></li>
<li>再运行 HelloWorldClient 将会在控制台看到grpc调用的远程返回结果</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/grpc/" rel="tag"># grpc</a>
          
            <a href="/tags/微服务/" rel="tag"># 微服务</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/23/grpc-composition/" rel="prev" title="grpc 生态体系简介">
                grpc 生态体系简介 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.png"
               alt="River" />
          <p class="site-author-name" itemprop="name">River</p>
           
              <p class="site-description motion-element" itemprop="description">闲来垂钓碧溪上，忽复乘舟梦日边</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">2</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">2</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/riverlee2014" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://gitee.com/river" target="_blank" title="码云">
                  
                    <i class="fa fa-fw fa-git"></i>
                  
                    
                      码云
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#基本原理"><span class="nav-number">2.</span> <span class="nav-text">基本原理</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Java示例入门"><span class="nav-number">3.</span> <span class="nav-text">Java示例入门</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#建立一个Maven工程"><span class="nav-number">3.1.</span> <span class="nav-text">建立一个Maven工程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#编写proto文件"><span class="nav-number">3.2.</span> <span class="nav-text">编写proto文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#代码示例"><span class="nav-number">3.3.</span> <span class="nav-text">代码示例</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">River</span>

  
</div>


  <div class="powered-by">
    由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
  </div>

  <span class="post-meta-divider">|</span>

  <div class="theme-info">
    主题 &mdash;
    <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
      NexT.Pisces
    </a>
  </div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  








  





  

  

  

  

  

  

</body>
</html>
